<template>
  <div class="auth-page">
    <div class="auth-container">
      <h2 class="title">用户登录</h2>

      <form @submit.prevent="handleSubmit" class="auth-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="form.username"
            type="text"
            placeholder="请输入用户名"
            required
          />
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            required
          />
        </div>

        <div class="form-actions">
          <button type="submit" class="submit-btn" :disabled="loading">
            {{ loading ? '登录中...' : '登录' }}
          </button>
          <div v-if="errorMessage" class="error-message">
            {{ errorMessage }}
          </div>
          <router-link to="/register" class="switch-link">没有账号？立即注册</router-link>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '@/api/auth'
import { useAuthStore } from '@/stores/useAuthStore'
import type { LoginResponse } from '@/types/auth'

interface LoginForm {
  username: string
  password: string
}

const router = useRouter()
const authStore = useAuthStore()

const form = reactive<LoginForm>({
  username: '',
  password: '',
})
const loading = ref(false)
const errorMessage = ref('')

const handleSubmit = async () => {
  // 前端验证
  if (!form.username || !form.password) {
    errorMessage.value = '请填写完整信息'
    return
  }

  try {
    loading.value = true
    errorMessage.value = ''

    // 调用登录API
    const response = await login({
      username: form.username,
      password: form.password,
    })

    // 处理API响应数据
    console.log('登录响应数据:', response) // 调试日志

    // 使用导入的LoginResponse类型
    const loginResponse = response as unknown as LoginResponse

    // 根据拦截器处理后的数据结构获取token
    const tokenData = {
      access: loginResponse.access,
      refresh: loginResponse.refresh,
    }

    if (!tokenData.access) {
      console.error('无效的token数据:', response)
      throw new Error('登录失败：无效的token响应')
    }

    // 使用authStore统一存储token
    authStore.setToken(tokenData.access)
    if (tokenData.refresh) {
      authStore.setRefreshToken(tokenData.refresh)
    }

    // 创建完整的User对象(登录接口只返回id和username)
    const userData = {
      id: loginResponse.user_id,
      username: loginResponse.username,
      email: '', // 登录接口不返回email，需要后续通过用户信息接口获取
    }
    authStore.setUser(userData)

    // 检查是否有重定向路径
    const redirectPath = router.currentRoute.value.query.redirect
    // 跳转到重定向路径或首页
    await router.push(redirectPath ? redirectPath.toString() : '/')
  } catch (error: any) {
    errorMessage.value = error.response?.data?.message || '登录失败，请稍后重试'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.auth-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;

  .auth-container {
    width: 400px;
    padding: 40px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    .title {
      text-align: center;
      margin-bottom: 30px;
      color: #333;
      font-size: 24px;
    }

    .auth-form {
      .form-group {
        margin-bottom: 20px;

        label {
          display: block;
          margin-bottom: 8px;
          font-size: 14px;
          color: #666;
        }

        input {
          width: 100%;
          padding: 12px;
          border: 1px solid #ddd;
          border-radius: 4px;
          font-size: 14px;

          &:focus {
            border-color: #f56c6c;
            outline: none;
          }
        }
      }

      .form-actions {
        display: flex;
        flex-direction: column;
        gap: 15px;

        .submit-btn {
          background: linear-gradient(to right, #ff4e50, #f9d423);
          color: white;
          border: none;
          padding: 12px;
          border-radius: 4px;
          font-size: 16px;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            opacity: 0.9;
          }
        }

        .error-message {
          color: #f56c6c;
          font-size: 14px;
          text-align: center;
          margin-top: 10px;
        }

        .switch-link {
          text-align: center;
          color: #f56c6c;
          font-size: 14px;
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
  }
}
</style>
